package com.bootdo.clouddo.service.book.impl;

import com.bootdo.clouddo.dao.book.BookBookmarkMapper;
import com.bootdo.clouddo.domain.book.BookBookmark;
import com.bootdo.clouddo.redis.CommonRedisService;
import com.bootdo.clouddo.redis.RedisEnum;
import com.bootdo.clouddo.service.book.IBookBookmarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookBookmarkServiceImpl implements IBookBookmarkService {

    @Autowired
    private BookBookmarkMapper dao;

    @Autowired
    private CommonRedisService redisService;


    @Override
    public int add(BookBookmark record) {
        int result = dao.insertSelective(record);
        if(result > 0) {
            clearCache(record.getBookId(), record.getSiteId(), record.getUid());
        }
        return result;
    }

    @Override
    public int delete(Long bookId, Integer siteId, String url, Long uid) {
        int result = dao.deleteByBook(bookId, siteId, url, uid);
        if(result > 0) {
            clearCache(bookId, siteId, uid);
        }
        return result;
    }

    @Override
    public List<BookBookmark> findByUid(Long bookId, Integer siteId, Long uid) {
        String key = RedisEnum.USER_BOOK_MARK.getKey() + bookId + "_" + siteId + "_" + uid;
        Optional<List> op = redisService.getAsOptional(key);
        if(op.isPresent()) {
            return op.get();
        }
        List<BookBookmark> data = dao.findByUid(bookId, siteId, uid);
        if(data != null) {
            redisService.put(key, data, RedisEnum.USER_BOOK_MARK.getExpire());
        }
        return data;
    }

    private void clearCache(Long bookId, Integer siteId, Long uid){
        redisService.remove(RedisEnum.USER_BOOK_MARK.getKey() + bookId + "_" + siteId + "_" + uid);
    }
}
